import 'package:hrf_app/common/utils/loading.dart';
import 'package:hrf_app/common/widgets/navigation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import 'index.dart';

class MainTabPage extends StatefulWidget {
  const MainTabPage({super.key});

  @override
  State<MainTabPage> createState() => _MainTabPageState();
}

class _MainTabPageState extends State<MainTabPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return const _MainViewGetX();
  }
}

class _MainViewGetX extends GetView<MainTabController> {
  const _MainViewGetX({Key? key}) : super(key: key);

  // 主视图
  Widget _buildView() {
    DateTime? lastPressedAt;
    return PopScope(
        canPop: false,
        // 防止连续点击两次退出
        onPopInvoked: (didPop) async {
          if (lastPressedAt == null ||
              DateTime.now().difference(lastPressedAt!) >
                  const Duration(seconds: 1)) {
            lastPressedAt = DateTime.now();
            Loading.toast('再按一次退出！');
            return;
          }
          await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
        },
        child: Scaffold(
          extendBody: true,

          resizeToAvoidBottomInset: false,
          bottomNavigationBar: GetBuilder<MainTabController>(
            id: 'navigation',
            builder: (controller) {
              return BuildNavigation(
                currentIndex: controller.currentIndex,
                items: controller.tabbarPermList,
                onTap: controller.onJumpToPage,
              );
            },
          ),
          body: PageView(
            physics: const NeverScrollableScrollPhysics(),
            controller: controller.pageController,
            onPageChanged: (index) {
              controller.onJumpToPage(index);
            },
            children: controller.tabbarPermPageList,
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MainTabController>(
        init: MainTabController(), id: "mainTab", builder: (_) => _buildView());
  }
}
